<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import { ElTable, ElMessageBox, FormInstance, type FormRules, ElMessage } from "element-plus"
import { formatDateTime } from "@/utils"
import { usePagination } from "@/hooks/usePagination"
import { Search, Refresh } from "@element-plus/icons-vue"
import { useRouter } from "vue-router"
import { useUserStore } from "@/store/modules/user"

// 接口
import {
  createCollectionDataApi,
  deleteCollectionDataApi,
  updateCollectionDataApi,
  getCollectionDataApi,
  cloenCollectionDataApi,
  createCollectionChilds
} from "@/api/combo-h5/recommend"
import { uploadComboImageList } from "@/api/combo"
import { useCommonStore } from "@/store/modules/common"
const commonStore = useCommonStore()
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
const userStore = useUserStore()

defineOptions({
  name: "Recommend"
})
const router = useRouter()
const compilationId = ref<any>(undefined)
/**图片上传相关 */
const fileList = ref<any>([]) /**图片列表 */
const dialogImageUrl = ref("") /**预览url  */
const dialogVisible1 = ref(false) /**预览弹窗 */
const handleChageImg = (file: any, resfileList: any) => {
  const size = ref(3)
  const fileSizeFlag = file.size / 1024 / 1024 < size.value
  if (!fileSizeFlag) {
    ElMessage.error(`请上传不大于${size.value}M的图片!`)
    fileList.value = []
  } else {
    fileList.value = resfileList
  }
}
const handlePictureCardPreview = (file: any) => {
  dialogImageUrl.value = file.url
  dialogVisible1.value = true
}
// 移除图片
const handleRemove = (file: any) => {
  const list = fileList.value
  for (const i in list) {
    if (list[i].uid === file.uid) {
      list.splice(i, 1)
    }
  }
  fileList.value = list
}
const handleUpdate = (row: any) => {
  compilationId.value = row.id
  formData.name = row.name
  formData.image = row.image
  if (row.image) {
    fileList.value = row.image?.split(",").map((item: any) => {
      return {
        url: `${commonStore.BASEURL}/image/${item}`
        // url: `http://192.168.31.143:8080/image/${item}`
      }
    })
  }
  dialogVisible.value = true
}
// #region  删
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`您确定要删除:${row.name}吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteCollectionDataApi(row.id).then(() => {
      ElMessage.success("删除成功")
      getApplet()
    })
  })
}
const handleCloen = (row: any) => {
  ElMessageBox.confirm(`您确定要克隆:${row.name}吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    cloenCollectionDataApi({ id: row.id }).then(() => {
      ElMessage.success("克隆成功")
      getApplet()
    })
  })
}
// #endregion

// #region 增
const formRef = ref<FormInstance | null>(null)
const formData = reactive({
  name: "",
  image: ""
})
const dialogVisible = ref<boolean>(false)
const rules: FormRules = reactive({
  name: [{ required: true, trigger: "blur", message: "请输入名称" }]
  // open: [{ required: true, trigger: "blur", message: "请选择是否对分销商开放" }]
})
const handleCreate = async () => {
  const fileData = new FormData()
  fileList.value.forEach((file: any) => {
    fileData.append("file", file.raw)
  })
  if (fileList.value.length && fileList.value[0].status === "ready") {
    await uploadComboImageList(fileData).then((res: any) => {
      if (res.code == 200) {
        formData.image = res.data.split("/image/")[1]
      }
    })
  }
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (compilationId.value === undefined) {
        createCollectionDataApi({
          name: formData.name,
          image: formData.image
        }).then(() => {
          ElMessage.success("新增成功")
          dialogVisible.value = false
          getApplet()
          fileList.value = []
        })
      } else {
        updateCollectionDataApi({
          id: compilationId.value,
          name: formData.name,
          image: formData.image
        }).then(() => {
          ElMessage.success("修改成功")
          dialogVisible.value = false
          getApplet()
          fileList.value = []
        })
      }
    } else {
      return false
    }
  })
}

const resetForm = () => {
  compilationId.value = undefined
  clearValidate()
  formData.name = ""
  formData.image = ""
  fileList.value = []
}
// #endregion

// #region 查
const loading = ref<any>(false)
const tableTotal = ref<number>()
const tableData = ref<any>([])
const getApplet = () => {
  getCollectionDataApi({
    page: paginationData.currentPage,
    size: paginationData.pageSize,
    name: searchData.name
  })
    .then((res: any) => {
      tableData.value = res.data.list
      tableTotal.value = res.data.total
      loading.value = false
    })
    .catch(() => {
      tableData.value = []
    })
}
// #endregion

// #region 搜索内容
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive<any>({
  name: ""
})
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getApplet()
  }
  paginationData.currentPage = 1
}
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getApplet()
  }
  paginationData.currentPage = 1
}
// #endregion

//跳转配置子套餐页面
const handleGoToChildSet = (row: any) => {
  console.log(row)
  router.push(`childsetRecom/?id=${row.id}`)
}

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getApplet, { immediate: true })
const clearValidate = () => {
  formRef.value?.clearValidate()
}
/**END */
// #region 所有团队
import { useTeamStore } from "@/store/modules/team"
const teamStore = useTeamStore()
const tableDataB = ref<any[]>([])
teamStore.getTeamFn()
watch(
  [() => teamStore.teamListStore],
  (newValue) => {
    tableDataB.value = newValue.flat()
  },
  { immediate: true }
)
const formatterTeam = (row: any, column: any, celValue: any) => {
  tableDataB.value.filter((item: any) => {
    if (item.id == row.teamId) {
      celValue = item.name
    }
  })
  return celValue
}

//批量配置子套餐
import { getComboDataApi } from "@/api/combo-h5"
const formDataChild = reactive({
  packageName: "",
  packageId: "",
  heImage: "",
  sort: ""
})
const comboList1 = ref<any>([])
const dialogVisiblePL = ref<boolean>(false)
const rulesPL = reactive<any>({
  packageId: [{ required: true, trigger: "blur", message: "请选择H5套餐" }]
})
const phIds = ref<any>([])
const formRefPL = ref<any>(null)
const getH5Data = () => {
  loading.value = true
  getComboDataApi({
    page: 1,
    size: 1000,
    teamId: userStore.usernameID
  })
    .then((res: any) => {
      comboList1.value = res.data.list.map((item: any) => {
        if (item.anotherName) {
          return {
            id: item.id,
            name: `${item.name}_${item.anotherName}`
          }
        } else {
          return {
            id: item.id,
            name: item.name
          }
        }
      })
    })
    .catch(() => {
      comboList1.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
getH5Data()
const handleSelectionChange = (val: any) => {
  if (val.length) {
    phIds.value = val
  }
}
const setItems = () => {
  dialogVisiblePL.value = true
  phIds.value = phIds.value.map((item: any) => {
    return item.id
  })
  console.log(phIds.value)
}
const resetFormPL = () => {
  formDataChild.packageId = ""
  formDataChild.sort = ""
  formDataChild.heImage = ""
  fileListPL.value = []
  formRefPL.value?.clearValidate()
}
/**子套餐图片上传相关 */
const fileListPL = ref<any>([]) /**图片列表 */
const dialogImageUrlPL = ref("") /**预览url  */
const dialogVisibleViewPL = ref(false) /**预览弹窗 */
const handleChageImgPL = (file: any, resfileList: any) => {
  const size = ref(3)
  const fileSizeFlag = file.size / 1024 / 1024 < size.value
  if (!fileSizeFlag) {
    ElMessage.error(`请上传不大于${size.value}M的图片!`)
    fileListPL.value = []
  } else {
    fileListPL.value = resfileList
  }
}
const handlePictureCardPreviewPL = (file: any) => {
  dialogImageUrlPL.value = file.url
  dialogVisibleViewPL.value = true
}
// 移除图片
const handleRemovePL = (file: any) => {
  const list = fileListPL.value
  for (const i in list) {
    if (list[i].uid === file.uid) {
      list.splice(i, 1)
    }
  }
  fileListPL.value = list
  formDataChild.heImage = ""
}
const handleCreatePL = async () => {
  const fileData = new FormData()
  fileListPL.value.forEach((file: any) => {
    fileData.append("file", file.raw)
  })
  if (fileListPL.value.length && fileListPL.value[0].status === "ready") {
    await uploadComboImageList(fileData).then((res: any) => {
      if (res.code == 200) {
        formDataChild.heImage = res.data.split("/image/")[1]
      }
    })
  }
  formRefPL.value?.validate((valid: boolean) => {
    if (valid) {
      if (!phIds.value.length) {
        ElMessage.warning("请选择合集")
        return false
      }
      createCollectionChilds({
        phId: phIds.value.join(),
        packageBackupId: formDataChild.packageId,
        sorts: formDataChild.sort,
        heImage: formDataChild.heImage
      }).then(() => {
        ElMessage.success("新增成功")
        dialogVisiblePL.value = false
        getApplet()
        fileListPL.value = []
      })
    } else {
      return false
    }
  })
}
</script>

<template>
  <div class="app-container">
    <el-card shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="name" label="名称">
          <el-input v-model.trim="searchData.name" clearable placeholder="请输入" style="width: 240px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 中间部分 -->
    <el-card v-loading="loading" shadow="never">
      <!-- 顶部添加 -->
      <div class="middle-top">
        <div>
          <el-button type="primary" @click="dialogVisible = true">添加推荐套餐</el-button>
          <el-button type="success" @click="setItems" style="display: none">批量配置子套餐</el-button>
        </div>
      </div>
      <!-- 中间渲染内容 -->
      <div class="table-center">
        <el-table :data="tableData" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="id" label="ID" align="center" />
          <el-table-column prop="create" label="创建时间" align="center">
            <template #default="scope">
              {{ formatDateTime(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="name" label="合集名称" align="center" />
          <el-table-column prop="teamId" label="团队名" align="center" :formatter="formatterTeam" />
          <el-table-column prop="createBy" label="创建人" align="center" />
          <el-table-column fixed="right" label="操作" width="150" align="left">
            <template #default="scope">
              <p>
                <el-button type="primary" text bg size="small" @click="handleGoToChildSet(scope.row)"
                  >配置子套餐</el-button
                >
              </p>
              <p>
                <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
              </p>
              <p><el-button type="primary" text bg size="small" @click="handleCloen(scope.row)">克隆</el-button></p>
              <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页器 -->
      <div class="pagination">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :page-size="paginationData.pageSize"
          :total="tableTotal"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="compilationId === undefined ? '新增' : '修改'"
      @close="resetForm"
      width="60%"
    >
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px" label-position="left">
        <el-form-item prop="name" label="名称" label-width="120">
          <el-input type="textarea" v-model="formData.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="image" style="display: none">
          <template #label>
            <span>合集头图</span>
            <el-tooltip class="box-item" effect="customized" placement="bottom">
              <template #content> 合集头图，用于产品合集页顶部图展示 建议尺寸 750 * 200 </template>
              <el-icon style="cursor: pointer"><InfoFilled /></el-icon>
            </el-tooltip>
          </template>
          <el-upload
            :auto-upload="false"
            :file-list="fileList"
            :show-file-list="true"
            list-type="picture-card"
            :limit="1"
            accept="image/*"
            :on-change="handleChageImg"
            :disabled="fileList.length != 0"
          >
            <el-icon><Plus /></el-icon>
            <template #file="{ file }">
              <div>
                <img class="el-upload-list__item-thumbnail" :src="file.url" />
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </span>
                  <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                    <el-icon>
                      <zoom-in />
                    </el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogVisible1">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
    <!-- 批量配置子套餐弹窗 -->
    <el-dialog v-model="dialogVisiblePL" title="批量配置子套餐" @close="resetFormPL" width="60%">
      <el-form ref="formRefPL" :model="formDataChild" :rules="rulesPL" label-width="100px" label-position="left">
        <el-form-item prop="packageId" label="H5套餐">
          <el-select
            v-model="formDataChild.packageId"
            clearable
            filterable
            placeholder="请选套餐,可输入快速查询"
            style="width: 100%"
          >
            <!-- :value="item.id + ''" -->
            <el-option v-for="item in comboList1" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="sort" label="排序">
          <el-input v-model="formDataChild.sort" placeholder="用合集页的排序,数字越小排名越靠前" />
        </el-form-item>
        <el-form-item prop="heImage">
          <template #label>
            <span>主图</span>
            <el-tooltip class="box-item" effect="customized" placement="bottom">
              <template #content> 主图，用于产品合集页产品的主图 </template>
              <el-icon style="cursor: pointer"><InfoFilled /></el-icon>
            </el-tooltip>
          </template>
          <el-upload
            :auto-upload="false"
            :file-list="fileListPL"
            :show-file-list="true"
            list-type="picture-card"
            :limit="1"
            accept="image/*"
            :on-change="handleChageImgPL"
            :disabled="fileListPL.length != 0"
          >
            <el-icon><Plus /></el-icon>
            <template #file="{ file }">
              <div>
                <img class="el-upload-list__item-thumbnail" :src="file.url" />
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-delete" @click="handleRemovePL(file)">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </span>
                  <span class="el-upload-list__item-preview" @click="handlePictureCardPreviewPL(file)">
                    <el-icon>
                      <zoom-in />
                    </el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisiblePL = false">取消</el-button>
        <el-button type="primary" @click="handleCreatePL">确认</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogVisibleViewPL">
      <img w-full :src="dialogImageUrlPL" alt="Preview Image" />
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
// .box-card {
//   height: 70px;
//   margin-bottom: 20px;
// }
.search-wrapper {
  margin-bottom: 20px;
}
.middle-top {
  margin-bottom: 20px;
}
.table-center {
  margin-bottom: 20px;
}
.pagination {
  display: flex;
  justify-content: flex-end;
}
</style>
<style>
.el-popper.is-customized {
  /* Set padding to ensure the height is 32px */
  padding: 6px 12px;
  background: linear-gradient(90deg, rgb(159, 229, 151), rgb(204, 229, 129));
}

.el-popper.is-customized .el-popper__arrow::before {
  background: linear-gradient(45deg, #b2e68d, #bce689);
  right: 0;
}
</style>
